package com.ikkong.qy.core;

import java.util.Map;

import com.ikkong.biz.model.Parent;
import com.ikkong.biz.model.Student;
import com.ikkong.biz.model.Teacher;
import com.ikkong.biz.model.WeixinUser;
import com.ikkong.core.constant.Cst;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.dao.Db;
import com.ikkong.core.jfinal.ext.kit.JStrKit;
import com.ikkong.core.toolbox.Record;
import com.ikkong.qy.util.TokenManager;
import com.ikkong.qy.util.WeixinApi;
import com.ikkong.qy.util.WeixinTicketManager;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

public class WeixinBaseController extends Controller {

	public Integer getUserType() {
		WeixinUser user = getUser();
		if (user instanceof Teacher) {
			return 1;
		} else if (user instanceof Parent) {
			return 2;
		} else {
			return 3;
		}
	}

	public WeixinUser getUser() {
		WeixinUser user = (WeixinUser) getSession().getAttribute("weixinUser");
		if (user == null) {
			String code = getPara("code");
		
			if (JStrKit.isBlank(code)) {
				return null;
			}
			synchronized (WeixinBaseController.class) {
				Record rec = Db.init()
						.queryMap("select v.* from v_weixin_users v where v.last_code = '" + code + "'", null);
				if (rec == null) {
					String wxId = WeixinApi.getWeixinUserIdByCode(code);
					
					rec = Db.init().queryMap("select v.* from v_weixin_users v where v.mobile = '"+wxId+"'",null);
					if (rec == null) {
						//处理未找到
					}else{
						String idStr = rec.getStr("id");
						String typeStr = rec.getStr("type");

						if (typeStr.equals("1")) { // 老师
							user = Blade.create(Teacher.class).findById(idStr);
						} else if (typeStr.equals("2")) { // 家长
							user = Blade.create(Parent.class).findById(idStr);
						}else  { // 学生
							user = Blade.create(Student.class).findById(idStr);
						}		
						user.setLast_code(code);
						Blade.create(user.getClass()).update(user);
						
						
						getSession().setAttribute("weixinUser",user);		
					}
					
					
				} else {
					String idStr = rec.getStr("id");
					String typeStr = rec.getStr("type");

					if (typeStr.equals("1")) { // 老师
						user = Blade.create(Teacher.class).findById(idStr);
					} else if (typeStr.equals("2")) { // 家长
						user = Blade.create(Parent.class).findById(idStr);
					}else  { // 学生
						user = Blade.create(Student.class).findById(idStr);
					}
					getSession().setAttribute("weixinUser",user);				
				}
			}
			
		}

		return user;
	}
	
	protected void createQyJsToken(){
		
	}
	
	protected void createJsToken(){
		WeixinApi.createQyChatJsToken(this);
	}

	public void renderNoUser() {

	}
}
